<template>
  <base-scroll ref="scroll"
    :options="scrollOptions"
    :data="tracks">
    <div class="ranklist">
      <base-loading-spinner v-if="loading"
        width="30px"
        height="30px"
        color="rgb(238, 10, 36)"
        itemWidth="8%"/>

      <div v-else>
        <song-list-poster :detail="detail" />
        <song-list-content
          :count="tracks.length"
          :collect="detail.subscribedCount"
          :tracks="tracks"
          @play-song="playSong"
          @update-playlist="updatePlaylist"/>
      </div>
    </div>
  </base-scroll>
</template>

<script>
import SongListContent from '@/components/SongListContent'
import SongListPoster from '@/components/SongListPoster'

export default {
  name: 'ranklist',
  components: {
    SongListContent,
    SongListPoster
  },
  data () {
    return {
      loading: true,
      tracks: [],
      detail: {
        coverImgUrl: '',
        name: '',
        id: '',
        updateTime: 0,
        avatarUrl: '',
        nickname: '',
        description: '',
        commentCount: 0,
        shareCount: 0,
        subscribedCount: 0
      },
      scrollOptions: {
        scrollX: false,
        scrollY: true,
        click: true,
        scrollbar: true
      }
    }
  },
  computed: {
    id () {
      return this.$route.params.id
    }
  },
  mounted () {
    this.getRank()
  },
  methods: {
    async getRank () {
      // Todo: 缓存至 storage
      let playlist
      this.loading = true
      if (this.$storage.hasCache(`toplist-${this.id}`)) {
        playlist = this.$storage.getItem(`toplist-${this.id}`).data
      } else {
        const res = await this.$api.getRankList(this.id)
        playlist = res.data.playlist
        // 将 playlist 属性缓存
        this.$storage.setItem(`toplist-${this.id}`, playlist, true, {
          maxAge: 5 * 60 * 1000
        })
      }

      this.loading = false
      this.tracks = playlist.tracks
      this.extractDetail(playlist)
    },
    extractDetail (data) {
      Object.keys(this.detail).map(v => {
        if (data[v]) {
          this.detail[v] = data[v]
        }
      })
      this.detail.avatarUrl = data.creator.avatarUrl
      this.detail.nickname = data.creator.nickname
    },
    playSong (song) {
      this.$store.dispatch('player/changeSong', { song, addPlaylist: false })
    },
    updatePlaylist () {
      this.$store.dispatch('player/updatePlaylist', {
        tracks: this.tracks,
        playlistId: this.id
      })
    }
  }
}
</script>
